package iamutkarshtiwari.github.io.ananas.editimage.fragment;

import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.ModuleConfig;
import iamutkarshtiwari.github.io.ananas.editimage.adapter.FilterAdapter;
import iamutkarshtiwari.github.io.ananas.editimage.fliter.PhotoProcessing;
import iamutkarshtiwari.github.io.ananas.editimage.utils.LogUtil;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.IOException;
import java.util.ArrayList;

public class FilterListFragment extends ComponentContainer {
    private static final int INDEX = ModuleConfig.INDEX_FILTER;
    private static final int NULL_FILTER_INDEX = 0;
    private static final String TAG = FilterListFragment.class.getName();

    private EditImageAbility editImageAbility;
    private PageSlider pageSlider;
    private ListContainer listContainer;
    private FilterAdapter itemProvider;

    private Component mainView;
    private PixelMap filterBitmap;
    private PixelMap currentBitmap;
    boolean changePixelmap = false;
//    private Dialog loadingDialog;

    public CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ArrayList<FilterAdapter.Item> items;

    /**
     * 构造
     *
     * @param context    Context对象
     * @param pageSlider PageSlider对象
     */
    public FilterListFragment(Context context, PageSlider pageSlider) {
        super(context);
        this.pageSlider = pageSlider;
        editImageAbility = (EditImageAbility) context;
        initView();

    }

    /**
     * 显示自定义视图
     */
    public void onShow() {
        editImageAbility.mode = EditImageAbility.MODE_FILTER;
        setCurrentBitmap(editImageAbility.getMainBit());
        editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());
        //由于listContainer scrollTo 不准，重设数据 刷新位置
        itemProvider = new FilterAdapter(mContext, this, items);
        listContainer.setItemProvider(itemProvider);
    }

    /**
     * 返回主视图
     */
    public void backToMain() {
//        editImageAbility.mainImage.setImageBitmap(editImageAbility.getMainBit());
//        editImageAbility.mode = EditImageAbility.MODE_NONE;
//        editImageAbility.bottomGallery.setCurrentItem(0);
//        editImageAbility.mainImage.setScaleEnabled(true);
//        editImageAbility.bannerFlipper.showPrevious();

        editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());
        editImageAbility.mode = EditImageAbility.MODE_NONE;
//        tryRecycleFilterBitmap();
        pageSlider.setCurrentPage(0, false);
        pageSlider.setVisibility(Component.HIDE);
        onDestroy();
        editImageAbility.saveOrApply(false);
    }

    /**
     * 应用修改
     */
    public void applyFilterImage() {
        if (currentBitmap == editImageAbility.getMainBit()) {
            backToMain();
        } else {
            PixelMap.InitializationOptions opt = new PixelMap.InitializationOptions();
            opt.pixelFormat = PixelFormat.RGB_565;
            editImageAbility.changeMainBitmap(PixelMap.create(filterBitmap, opt), true);
            backToMain();
        }
    }

    private void initView() {
        Component component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_fragment_filter_layout, null, false);
        addComponent(component);

        //返回
        findComponentById(ResourceTable.Id_back_to_main).setClickedListener(component1 -> backToMain());

        String[] filters;
        String[] filterImages;
        try {
            filters = getResourceManager().getElement(ResourceTable.Strarray_iamutkarshtiwari_github_io_ananas_filters).getStringArray();
            filterImages = getResourceManager().getElement(ResourceTable.Strarray_iamutkarshtiwari_github_io_ananas_filter_drawable_list).getStringArray();

            if (filters.length != filterImages.length) {
                filters = null;
                filterImages = null;
            }
        } catch (IOException | NotExistException | WrongTypeException e) {
            filters = null;
            filterImages = null;
        }

        items = new ArrayList<>();
        for (int i = 0; i < filters.length; ++i) {
            items.add(new FilterAdapter.Item(filters[i], filterImages[i]));
        }

        itemProvider = new FilterAdapter(mContext, this, items);

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_filter_recycler);
        listContainer.setOrientation(Component.HORIZONTAL);
        listContainer.setItemProvider(itemProvider);

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                if (!changePixelmap) {
                    enableFilter(i);
                }
            }
        });
    }

    //    @Override
    public void onDestroy() {
        tryRecycleFilterBitmap();
    }

    private void tryRecycleFilterBitmap() {
        if (filterBitmap != null && (!filterBitmap.isReleased())) {
            filterBitmap.release();
        }
    }

    /**
     * 滤镜效果生效
     *
     * @param filterIndex 滤镜index
     */
    public void enableFilter(int filterIndex) {
        if (filterIndex == NULL_FILTER_INDEX) {
            editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());//setImageBitmap
            currentBitmap = editImageAbility.getMainBit();
            return;
        }
        compositeDisposable.clear();
        Disposable applyFilterDisposable = applyFilter(filterIndex)
                .subscribeOn(Schedulers.computation())
//                .observeOn(Schedulers.mainThread()  )
//                .doOnSubscribe(subscriber -> loadingDialog.show())
//                .doFinally(() -> loadingDialog.dismiss())
                .subscribe(
                        this::updatePreviewWithFilter,
                        e -> showSaveErrorToast()
                );
        compositeDisposable.add(applyFilterDisposable);
    }

    private void updatePreviewWithFilter(PixelMap bitmapWithFilter) {
        if (bitmapWithFilter == null) return;

        if (filterBitmap != null && (!filterBitmap.isReleased())) {
            filterBitmap.release();
        }

        filterBitmap = bitmapWithFilter;
        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                editImageAbility.mainImage.setPixelMap(filterBitmap);//setImageBitmap
                changePixelmap = false;
                itemProvider.loadingView.hide();
            }
        });
        currentBitmap = filterBitmap;
    }

    private void showSaveErrorToast() {
    }

    private Single<PixelMap> applyFilter(int filterIndex) {
        changePixelmap = true;
        itemProvider.loadingView.show(itemProvider.roundProgress);
        return Single.fromCallable(() -> {
            PixelMap.InitializationOptions opt = new PixelMap.InitializationOptions();
            opt.pixelFormat = PixelFormat.RGB_565;
            opt.editable = true;

            PixelMap srcBitmap = PixelMap.create(editImageAbility.getMainBit(), opt);
            return PhotoProcessing.filterPhoto(srcBitmap, filterIndex);
        });
    }

    private void setCurrentBitmap(PixelMap currentBitmap) {
        this.currentBitmap = currentBitmap;
    }
}
